﻿Public Class SortableListView
    Inherits ListView

    Dim SortColumn As Integer = -1
    Private Sub SortableListView_ColumnClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) Handles Me.ColumnClick
        If e.Column <> SortColumn Then
            SortColumn = e.Column
            Me.Sorting = SortOrder.Ascending
        Else
            If Me.Sorting = SortOrder.Ascending Then
                Me.Sorting = SortOrder.Descending
            Else
                Me.Sorting = SortOrder.Ascending
            End If
        End If

        Me.ListViewItemSorter = New ListViewItemComparer(e.Column, Me.Sorting)
        Me.Sort()
    End Sub

    Class ListViewItemComparer
        Implements IComparer
        Private Column As Integer
        Private Order As SortOrder

        Public Sub New()
            Column = 0
            Order = SortOrder.Ascending
        End Sub

        Public Sub New(ByVal column As Integer, ByVal order As SortOrder)
            Me.Column = column
            Me.Order = order
        End Sub

        Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
            Dim returnVal As Integer = -1

            Try
                Dim ix As Integer = CType(CType(x, ListViewItem).SubItems(Column).Text, Integer)
                Dim iy As Integer = CType(CType(y, ListViewItem).SubItems(Column).Text, Integer)

                If ix > iy Then
                    returnVal = 1
                Else
                    returnVal = -1
                End If
            Catch ex As Exception
                returnVal = [String].Compare(CType(x, ListViewItem).SubItems(Column).Text, CType(y, ListViewItem).SubItems(Column).Text)
            End Try

            If Order = SortOrder.Descending Then
                returnVal *= -1
            End If

            Return returnVal
        End Function
    End Class
End Class
